<template>
  <div>
    <!-- 用户查询界面 -->
    <div>
      <div class="searchArea">
        <LoginInput class="margin-20" title="请输入想要查询的用户名" type="text" v-model="params.name" />
        <div class="btns">
          <LoginButton type="0" class="margin-10" title="查询" @click="()=>{bySearchName();this.params.pageNum = 1}" />
          <LoginButton type="2" class="margin-10" title="新增" @click="isAddShow=true" />
          <LoginButton type="3" class="margin-10" title="删除" @click="deleteUser()" />
        </div>
      </div>

      <table class="shadow">
        <thead>
          <tr>
            <td></td>
            <td>编号</td>
            <td>头像</td>
            <td>用户名</td>
            <td>角色权限</td>
            <td>邮箱</td>
            <td>创建时间</td>
            <td>用户状态</td>
            <td>操作</td>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(u, index) in users" :key="index">
            <td>
              <el-checkbox v-model="u.isChecked" v-if="currentUser.userId != u.userId" />
            </td>
            <td>{{ index + (params.pageNum - 1) * params.pageSize +1}}</td>
            <td>
              <div class="imgBar">
                <img :src="u.userImg" alt="tx" height="50">
              </div>
            </td>
            <td>{{ u.userName }}</td>
            <td>
              <span class="common">
                {{ $store.state.authTable[u.authId-1]?.name }}
              </span>
            </td>
            <td>{{ u.userEmail }}</td>
            <td>{{ u.registrationDate }}</td>
            
            <td :style="{'color': u.userState==0?'green':'brown'}">
              <span :class="{'online': u.userState==0, 'offline': u.userState!=0}">
                {{ u.userState == 0 ? '在线' : '离线' }}
              </span>
            </td>
            

            <!-- 操作 -->
            <td>
              <ul>
                <!-- <li>
                  <span>分配权限</span>
                </li> -->
                <li>
                  <span
                  @click="resetPassword(u)"
                  >重置密码</span>
                </li>
                <li>
                  <span
                  @click="editShow(u)"
                  >编辑</span>
                </li>
                <li v-if="currentUser.userId != u.userId">
                  <span 
                    @click="$store.dispatch('deleteUser',{userList: [u], vm: this})"
                  >
                    删除
                  </span>
                </li>
              </ul>
            </td>

          </tr>
          <tr v-if="users?.length == 0">
            <td>....</td>
            <td>....</td>
            <td>.......</td>
            <td style="color: #b10c7a;">什么也没查到捏 <span style="color: #2151f1;">┑(￣Д ￣)┍</span></td>
            <td>....</td>
            <td>....</td>
            <td>....</td>
            <td>....</td>
            <td>....</td>
          </tr>
        </tbody>
      </table>
      <!--分页-->
      <div class="demo-pagination-block" style="margin-top: 10px;">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="params.pageNum"
          :page-sizes="[5, 10, 15, 20]" :page-size="params.pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
  </div>
  
  <!-- 编辑 -->
  <el-dialog 
    v-model="isEditShow" 
    title="编辑" 
    style="width: 500px; border-radius: 15px;"
  >
    <el-form :model="editForm" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="editForm.userName" style="width: 250px;"/>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="editForm.userEmail" style="width: 250px;"/>
      </el-form-item>
      <el-form-item label="用户权限">
        <el-select v-model="editForm.authId" placeholder="选择用户权限" style="width: 150px;">
          <el-option 
            v-for="(a, index) in $store.state.authTable" 
            :key="index" 
            :label="a.name" 
            :value="a.id" 
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="editForm.registrationDate"
          type="datetime"
          placeholder="选择日期与时间"
          style="width: 250px;"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <el-form-item label="用户状态">
        <el-select v-model="editForm.userState" placeholder="选择用户状态" style="width: 150px;">
          <el-option label="在线" value="0" />
          <el-option label="离线" value="1" />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isEditShow = false">取消</el-button>
        <el-button type="primary" @click="editUserInfo()">
          保存
        </el-button>
      </span>
    </template>

  </el-dialog>

  <!-- 新增用户 -->
  <el-dialog 
    v-model="isAddShow" 
    title="新增用户" 
    style="width: 500px; border-radius: 15px;"
  >
    <div style="text-align: center; margin-bottom: 50px;">tip：默认密码为123456</div>

    <el-form :model="editForm" label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="addForm.userName" style="width: 250px;" placeholder="请输入要新增的用户名"/>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="addForm.userEmail" style="width: 250px;" placeholder="请输入要新增的邮箱"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="isAddShow = false">取消</el-button>
        <el-button type="primary" @click="addUser()">
          保存
        </el-button>
      </span>
    </template>

  </el-dialog>

</template>

<script>
import LoginInput from '../Others/LoginInput.vue';
import LoginButton from '../Others/LoginButton.vue';
import { ElMessageBox } from 'element-plus'
import request from '@/utils/request';


export default {
  name: 'UserManagePage',
  components: {
    LoginInput,
    LoginButton,
  },
  data() {
    return {
      params: {
        name: "",
        pageNum:1,
        pageSize:10,
        searchType: 0
      },
      users: [],
      total:0,
      isEditShow: false,
      isAddShow: false,
      editForm:{},
      addForm:{},
    }
  },
  computed:{
    currentUser(){
      return this.$store.getters.currentUser
    }
  },
  created() {
    this.load();
  },

  methods:
  {
    load() {
     request.get("/api/start/list", {
        params: this.params
      }).then(res => {
        if (res.code === 200) {
          console.log(res)
          this.users = res.data.records;
          this.total=res.data.total;
        } else {
          console.log("出了一些神秘的问题");
        }
      },
      error => {
          console.log(error.message);
          this.$message({
            message: '连接错误',
            type: 'error'
          })
        })    
    },
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      /* this.params.pageNum++ */
      this.findSearch()
      
    },
    handleCurrentChange(pageNum) {
      this.params.pageNum = pageNum;
      /* this.params.pageNum++ */
      this.findSearch()
    },
    /* 重置密码 */
    resetPassword(user){
      ElMessageBox.confirm(
        '您正在 重置 这个账号的登录密码(默认密码123456)，这个操作不可挽回，确认要继续吗?',
        '提示',
        {
          confirmButtonText: '继续',
          cancelButtonText: '算了吧',
          type: 'warning',
        }
      ).then(() => {
          /* 确认后重置账号密码 */
          request.post("/api/start/reset", {userId:user?.userId, registrationDate: user?.registrationDate}).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
            } else {
              this.$message({
                message: res.msg,
                type: 'error'
              });
            }
          })
        }).catch(() => {
        this.$message({
          message: '密码重置已取消',
          type: 'info'
        });
      })
    },
    /* 批量删除被勾选的用户 */
    deleteUser(){
      let userList = []
      this.users.forEach(u => {
        if(u.isChecked) userList.push(u)
      });
      if(userList.length == 0){
        this.$message({
          message: "您还没有选择任何用户",
          type: 'error'
        })
        return
      }

      this.$store.dispatch('deleteUser',{userList, vm: this})
    },
    
    /* 通过用户名搜索 */
    bySearchName() {
      this.params.searchType = 1
      request.get("/api/start/list", {
        params: this.params
      }).then(
        res => {
          if (res.code === 200) {
            this.users = res.data.records;
            this.total = res.data.total
          } else {
            console.log("出了一些神秘的问题");
          }
        },
        error => {
          console.log(error.message);
          this.$message({
            message: '连接错误',
            type: 'error'
          })
        }
      )
    },
    /* 新增用户 */
    addUser(){
      request.post("/api/start/add", {
        userName: this.addForm.userName,
        userEmail: this.addForm.userEmail,
      }).then(
        res => {
          console.log(res.code);
          if (res.code === 200) {
            this.$message({
              message:'操作成功!',
              type:'success'
            })
            this.findSearch()
            this.addForm.userName = ''
            this.addForm.userEmail = ''
            this.isAddShow = false;
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },
        error => {
          console.log(error.message);
          this.$message({
            message: '连接错误',
            type: 'error'
          })
        }
      )
    },
    /* 显示编辑窗口 */
    editShow(u){
      this.isEditShow = true
      this.editForm.userName = u.userName
      this.editForm.userState = u.userState.toString()
      this.editForm.authId = u.authId
      this.editForm.registrationDate = u.registrationDate
      this.editForm.userId = u.userId
      this.editForm.userEmail = u.userEmail
    },
    editUserInfo(){
      request.post("/api/start/edit", {
        userId: this.editForm.userId,
        userName: this.editForm.userName,
        userState: this.editForm.userState,
        authId: this.editForm.authId,
        userEmail: this.editForm.userEmail,
        registrationDate: this.editForm.registrationDate,
      }).then(
        res => {
          if (res.code === 200) {
            this.$message({
              message:'修改成功!',
              type:'success'
            })
            this.findSearch()
            this.isEditShow = false;
          } else {
            this.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },
        error => {
          console.log(error.message);
          this.$message({
            message: '连接错误',
            type: 'error'
          })
        }
      )
    },
    findSearch(){
      switch(this.params.searchType){
        case 0:
          this.load()
          break
        case 1:
          this.bySearchName();
          break
        case 2:
          this.bySearchRegistrationDate()
          break
        case 3:
          this.bySearchState()
          break
        default:
          break
      }
    }

  }

}
</script>

<style scoped lang="less">
.demo-pagination-block {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.title {
  font-size: 40px;
  padding-top: 20px;
  font-weight: bold;
  color: rgb(0, 0, 70);
  font-style: italic;
  line-height: 120px;
  padding-left: 20px;
}

header .user-drop-list {
  position: absolute;
  right: 20px;
  top: -20px;
  left: auto;
}

.imgBar {
  height: 40px;
  width: 40px;
  border-radius: 50%;
  overflow: hidden;
}
.imgBar img {
  height: 100%;
  width: 100%;
}

.container {
  background-color: rgba(255, 255, 255, 0.5);
  height: 100vh;
  padding-top: 10px;
}

.searchArea {
  display: flex;
  width: 100%;
  border-bottom: 1px solid rgba(0, 0, 0, 0.3);
}

.btns {
  margin-top: 15px;
}

table {
  margin-top: 10px;
  width: 100%;
  background-color: rgb(199, 199, 199);
  border-radius: 10px;
  border-collapse: collapse;
  overflow: hidden;

  tbody {
    font-size: 15px;

    tr:nth-child(2n+1) {
      background-color: rgb(228, 228, 228);
    }

    tr:hover {
      background-color: rgb(255, 255, 255);
    }
  }

  tr {
    height: 50px;
  }

  tr td {
    padding-left: 10px;
    padding-top: 5px;
    padding-bottom: 5px;
  }

  thead {
    font-weight: bold;
  }


  /* 在线状态 */
  .online {
    background-color: rgba(63, 221, 0, 0.2);
    border-radius: 6px;
    border: 1px solid rgba(1, 167, 37, 0.5);
    color: rgb(14, 172, 0);
    padding: 4px 8px;
  }
  .offline {
    background-color: rgba(255, 30, 0, 0.2);
    border-radius: 6px;
    border: 1px solid rgba(243, 52, 27, 0.5);
    color: rgb(172, 20, 0);
    padding: 4px 8px;
  }

  /* 用户权限 */
  .common {
    background-color: rgba(167, 167, 167, 0.2);
    border-radius: 6px;
    border: 1px solid rgba(46, 46, 46, 0.5);
    color: rgb(73, 73, 73);
    padding: 4px 8px;
  }
  .root {
    background-color: rgba(167, 167, 167, 0.2);
    border-radius: 6px;
    border: 1px solid rgba(46, 46, 46, 0.5);
    color: rgb(73, 73, 73);
    padding: 4px 8px;
  }
  
  /* 操作 */
  li {
    float: left;
    font-size: 15px;
    padding: 0 10px;
    color: rgb(38, 105, 230);
    height: 15px;
    line-height: 15px;
    border-right: 1px solid rgb(155, 155, 155);
    
    span {
      cursor: pointer;
    }
    span:hover {
      color: rgb(5, 42, 110);
      text-decoration: underline;
    }
  }
  li:last-child {
    padding-right: 0;
    border-right: 0;
  }

  li:first-child {
    padding-left: 0;
  }

  ul {
    list-style: none;
  }
}

/* 编辑窗口 */
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
